#!/usr/bin/env bash

# PACKAGE: Gunther
# VERSION: 2.0
# DATE: 12/20/08
# AUTHOR(S): Zarrar Shehzad

# Checks an fsf file

# INCLUDE
source "$GUNTHERDIR/include/Asourceall.sh"

# Variables
fsfFile=""

# Functions
## USAGE
function usage {
    changegood green
    echo
    echo "Usage"
    echo "  $0 <fsf file> <skip check -> don't check for output feat directory (0 or 1, default is 0)> <force -> overwrite output feat (0 or 1, default is 0)>"
    echo "Program:"
    echo "   Checks an fsf file"
    echo
    changebad
}
## Participant Analysis Check
function participantCheck {
    ## Check the output feat directory
    echo -n "."
    if [[ "$feat_to_skip" == 0 ]]; then
        featDir=$( x_fsfinfo.sh "set fmri(outputdir)" ${fsfFile} | sed s/\\.feat$// ).feat
        if [[ -d "$featDir" ]]; then
            if [[ "$feat_to_remove" == 1 ]]; then
                znotice "Removing output feat directory '${featDir}'"
                zcmd "rm -r ${featDir}"
            else
                zerror "Output feat directory '${featDir}' exists"
                exit -1
            fi
        fi
    fi

    ## Check the input functional files
    echo -n "."
    funcFile=( $( x_fsfinfo.sh "set feat_files" ${fsfFile} ) )
    if [[ "${#funcFile[@]}" == 1 ]]; then
        funcFile=${funcFile%.$gOUTPUT_TYPE}.${gOUTPUT_TYPE}
        if [[ ! -e "${funcFile}" ]]; then
            zerror "Functional file '${funcFile}' not found"
            exit -1
        else
            ### get the vols in functional file
            numVols=$( fslnvols ${funcFile} )
        fi
    else
        zerror "This script is intended to check an fsf with only one functional file as input and not ${#funcFile[@]}"
        exit -1
    fi

    ## Check the ev input files
    echo -n "."
    evFiles=( $( x_fsfinfo.sh "set (custom" ${fsfFile} ) )
    for evFile in ${evFiles[@]}; do
        zinfo "Checking EV file '${evFile}'"
        if [[ ! -e "$evFile" ]]; then
            zerror "EV file '${evFile}' not found"
            exit -1
        fi
        x_checkTs.sh -i ${evFile} -v ${numVols}
        if [[ "$?" != 0 ]]; then
            exit -1
        fi
    done

    ## Check if doing registration
    if [[ $( x_fsfinfo.sh "set fmri(reg_yn)" ${fsfFile} ) == 1 ]]; then
        ### Check input anatomical files
        echo -n "."
        anatFile=( $( x_fsfinfo.sh "set highres_files" ${fsfFile} ) )
        if [[ "${#anatFile[@]}" == 1 ]]; then
            anatFile=${anatFile%.$gOUTPUT_TYPE}.${gOUTPUT_TYPE}
            if [[ ! -e "${anatFile}" ]]; then
                zerror "Anatomical/high-res file '${anatFile}' not found"
                exit -1
            fi
        elif [[ ${#anatFile[@]} != 0 ]]; then
            zerror "This script is intended to check an fsf with only one anatomical file as input and not ${#anatFile[@]}"
            exit -1
        fi
        ### Check input stanard file
        echo -n "."
        standardFile=$( x_fsfinfo.sh "set regstandard" ${fsfFile} )
        if [[ ! -z "$standardFile" ]]; then
            standardFile=${standardFile%.$gOUTPUT_TYPE}.${gOUTPUT_TYPE}
            if [[ ! -e "$standardFile" ]]; then
                zerror "Standard anatomical file '${standardFile}' not found"
                exit -1
            fi
        fi
    fi

    ## Check the tr
    echo -n "."
    funcTR=$( fslinfo ${funcFile} | grep "pixdim4" | awk '{print $2}' )
    fsfTR=$( x_fsfinfo.sh "set fmri(tr)" ${fsfFile} )
    if [[ $( echo "$funcTR != $fsfTR" | bc ) == 1 ]]; then
        zwarn "The TR of the functional file '${funcFile}' does not match with the TR given in the fsf file '${fsfFile}'"
    fi

    ## Check the npts
    echo -n "."
    fsfVols=$( x_fsfinfo.sh "set fmri(npts)" ${fsfFile} )
    if [[ "$numVols" != "$fsfVols" ]]; then
        zerror "Number of volumes in input functional file '${funcFile}' ($numVols) is not the same as the number of volumes specified in the fsf file '${fsfFile}' ($fsfVols)"
    fi
    
    return 0
}

## Group Analysis Check
function groupCheck {
    ## Check the output gfeat directory
    echo -n "."
    if [[ "$feat_to_skip" == 0 ]]; then
        featDir=$( x_fsfinfo.sh "set fmri(outputdir)" ${fsfFile} | sed s/\\.gfeat$// ).gfeat
        if [[ -d "$featDir" ]]; then
            if [[ "$feat_to_remove" == 1 ]]; then
                znotice "Removing output feat directory '${featDir}'"
                zcmd "rm -r ${featDir}"
            else
                zerror "Output feat directory '${featDir}' exists"
                exit -1
            fi
        fi
    fi

    ## Check the input feat directories or functional files
    echo -n "."
    numFuncFiles=$( grep "set feat_files" ${fsfFile} | wc -l )
    funcFiles=( $( x_fsfinfo.sh "set feat_files" ${fsfFile} ) )
    if [[ "$numFuncFiles" != ${#funcFiles[@]} ]]; then
        zerror "One or more feat directories or files were not given, check '${fsfFile}'"
        exit -1
    fi
    for (( i = 0; i < ${numFuncFiles}; i++ )); do
        funcFile="${funcFile[$i]}"
        ### Setup extension of file (depends on input type)
        if [[ "$inputType" == 1 ]]; then
            funcFile=${funcFile%.feat}.feat
            # check main directory
            if [[ ! -d "${funcFile}" ]]; then
                zerror "Feat directory '${funcFile}' not found"
                exit -1
            fi
            # check reg directory
            if [[ ! -d "${funcFile}/reg" ]]; then
                zwarn "No registration directory in '${funcFile}'"
            fi
            # check stats directory
            if [[ ! -d "${funcFile}/stats" ]]; then
                zwarn "No stats directory found in '${funcFile}'"
            fi
        else
            funcFile=${funcFile&.$gOUTPUT_TYPE}.${gOUTPUT_TYPE}
            # check file
            if [[ ! -e "${funcFile}" ]]; then
                zerror "Functional file '${funcFile}' not found"
                exit -1
            fi
        fi
    done
    
    return 0
}

# Check input
if [[ "$#" -lt 1 ]]; then
    usage
    exit 2
else
    fsfFile="$1"
    feat_to_skip="${2:-0}"
    feat_to_remove="${3:-0}"
fi

## Check the level of analysis
levelAnalysis=$( x_fsfinfo.sh "set fmri(level)" ${fsfFile} )

## Check participant
if [[ "$levelAnalysis" == 1 ]]; then
    ztitle "Checking participant fsf file: ${fsfFile}"
    ### run function at top
    participantCheck
### Check group
elif [[ "$levelAnalysis" == 2 ]]; then
    ztitle "Checking group fsf file: ${fsfFile}"
    ## run function at top
    groupCheck
else
    zemerg "Level of analysis in fsf '${fsfFile}' unknown!"
    exit -2
fi

echo "done!"
